﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Drawing;

namespace TRIG_MOD_STATUSSUMMARY.TCE_StatusSummaries
{
    public partial class TCE_StatusSummariesUserControl : UserControl
    {

        DataForStatusSummary objCls = new DataForStatusSummary();
        bool bexport = false;

        SPSite oSite;
        SPWeb oWeb;

        string Types;
        List<string> docTypes = new List<string>();
        List<string> discipAbb = new List<string>();

        public List<string> DocTypes
        {
            get { return docTypes; }
            set { docTypes = value; }
        }

        public List<string> Disciplines
        {
            get { return discipAbb; }
            set { discipAbb = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                Types = Request.QueryString["Source"];
                objCls.Types = Types;
                if (!IsPostBack)
                {
                    docTypes.Clear();
                    ddlDocsTypes.Items.Clear();
                    DocTypes = objCls.GetDocumentType(ddlDocsTypes);
                    ddlDocsTypes.Items.Add("Inspection Requests");

                }
                Disciplines.Clear();
                Disciplines = objCls.GetDiscipiline();
                Nulls();
            }
            catch (Exception x)
            {
                errorMessage.Text += x.Message;
            }
            DateValidation();

        }

        private void DateValidation()
        {

            if (Convert.ToInt32(rdDates.SelectedItem.Value) == 0)
            {
                stDt.MaxDate = DateTime.Today;
                stDt.SelectedDate = DateTime.Today;
                stDt.Enabled = false;
                stDt.IsRequiredField = true;
                endDt.IsValid = false;


            }
            else
            {
                //endDT.Visible = true;

                stDt.IsRequiredField = true;
                endDt.IsRequiredField = true;
            }
        }

        private void Process_DR()
        {
            NullLabels_DR();
            discipAbb = objCls.GetDiscipiline();
            objCls.CreateTable("DR");
            if (Convert.ToInt32(rdDates.SelectedItem.Value) == 1)
                GetDates_DR();
            else
                GetDates_DR("Today");
            objCls.rdDates = rdDates;
            objCls.grid = stSumGrid;

            objCls.GetDocItemsbyDiscipiline(ddlDocsTypes.SelectedItem.Text, Disciplines, errorMessage, "DR");
            objCls.BindGrid(stSumGrid, "DR");
        }

        private void Process_IR()
        {
            NullLabels();
            SetGetDates();
            //string Type = "CNT";
            string Type = Types;
            if (Type == "CNS")
            { objCls.CreateTable("IR_CNT"); objCls.Group = ("CNT"); }
            else { objCls.CreateTable("IR_CNS"); objCls.Group = ("CNS"); }

            int ck = objCls.GetDocItemsbyDiscipiline_MM(ddlDocsTypes.SelectedItem.Text, Disciplines, errorMessage, "MM");
            if (ck > 0)
                objCls.BindGrid(stSumGrid, "MM");
            else { }
            
        }

        private void Process_IRS()
        {
            NullLabels();
            SetGetDates();
            //string Type = "CNT";
            string Type = Types;
            if (Type == "CNS")
            { objCls.CreateTable("IRS_CNT"); objCls.Group = ("CNT"); }
            else { objCls.CreateTable("IRS_CNS"); objCls.Group = ("CNS"); }

            int ckData = objCls.GetDocItemsbyDiscipiline(ddlDocsTypes.SelectedItem.Text, errorMessage, "IR");
            if (ckData > 0)
            {
                objCls.BindGrid(stSumGrid, "IR");
                stSumGrid.Visible = true;
            }
            else { }
        }

        private void Process_DS()
        {
            NullLabels();
            SetGetDates();
            objCls.CreateTable("DS");
            objCls.Group = ("CNT");
            int ck = objCls.GetDocItemsbyDiscipiline_DS(ddlDocsTypes.SelectedItem.Text, Disciplines, errorMessage, "DS");
            if (ck > 0)
            {

                objCls.BindGrid(stSumGrid, lbl_R1, lbl_R2, lbl_R3, lbl_R4, lbl_R5, "DS");
                string p = " % of MSs ";
                lblr1.Text = "Under Review" + p;
                lblr2.Text = "Approved (Code : 1) as per total submitted" + p;
                lblr3.Text = "Approved as noted (Code : 2) as per total submitted" + p;
                lblr4.Text = "Not Approved (Code : 3) as per total submitted" + p;
                lblr5.Text = "Superseded as per total submitted" + p;
            }
            else { }

        }

        private void Process_DOC()
        {
            NullLabels();
            SetGetDates();
            objCls.CreateTable("contractor");
            objCls.Group = ("CNT");
            int ck = objCls.GetDocItemsbyDiscipiline_DSS(ddlDocsTypes.SelectedItem.Text, Disciplines, errorMessage, "DSS");
            if (ck > 0)
            {
                objCls.BindGrid(stSumGrid, lbl_R1, lbl_R2, lbl_R3, lbl_R4, lbl_R5, "DSS");
                if (stSumGrid.Rows.Count > 1)
                {
                    string p = "% of MSs ";
                    lblr1.Text = "Under Review" + p;
                    lblr2.Text = "Approved (Code : 1) as per total submitted" + p;
                    lblr3.Text = "Approved as noted (Code : 2) as per total submitted" + p;
                    lblr4.Text = "Not Approved (Code : 3) as per total submitted" + p;
                    lblr5.Text = "Superseded as per total submitted" + p;
                }
                else { lblr1.Text = ""; lblr2.Text = ""; lblr3.Text = ""; lblr4.Text = ""; lblr5.Text = ""; lbl_R1.Text = ""; lbl_R2.Text = ""; lbl_R3.Text = ""; lbl_R4.Text = ""; lbl_R5.Text = ""; }
            }
            else { }
        }

        private void SetGetDates()
        {
            objCls.grid = stSumGrid;
            objCls.rdDates = rdDates;
            if (Convert.ToInt32(rdDates.SelectedItem.Value) == 1) // Between Dates
                GetDates();
            else { }
            //GetDates("Today");

        }

        private void GetDates(string today)
        {
            string startDt = Convert.ToString(stDt.SelectedDate.ToShortDateString());
            objCls.cpStDT = startDt;
            objCls.cpEndDT = startDt;

        }

        private void GetDates()
        {
            //stDT.IsRequiredField = true;
            //endDT.IsRequiredField = true;
            string startDt = Convert.ToString(stDt.SelectedDate.ToShortDateString());
            string endDts = Convert.ToString(endDt.SelectedDate.ToShortDateString());
            objCls.cpStDT = startDt;
            objCls.cpEndDT = endDts;

        }

        private void GetDates_DR()
        {
            string thisMonthStart = Convert.ToString(stDt.SelectedDate.ToShortDateString());
            DateTime tmStDt = Convert.ToDateTime(thisMonthStart);
            thisMonthStart = Convert.ToString(tmStDt.AddDays(1 - tmStDt.Day));
            string thisMonthToday = Convert.ToString(new DateTime(tmStDt.Year, tmStDt.Month, 1).AddMonths(1).AddDays(-1)); //DateTime.Now.ToLongTimeString();
            //var yr = DateTime.Today.Year;
            //var mth = DateTime.Today.Month;
            var yr = stDt.SelectedDate.Year;
            var mth = stDt.SelectedDate.Month;
            var firstDay = new DateTime(yr, mth, 1).AddMonths(-1);
            var lastDay = new DateTime(yr, mth, 1).AddDays(-1);
            string lastMonthStart = Convert.ToString(firstDay);
            string lastMonthEnd = Convert.ToString(lastDay);

            objCls.cpStDT = thisMonthStart;
            objCls.cpEndDT = thisMonthToday;
            objCls.lpStDt = lastMonthStart;
            objCls.lpEndDt = lastMonthEnd;
        }

        private void GetDates_DR(string today)
        {
            string todays = Convert.ToString(stDt.SelectedDate.ToShortDateString());
            string yesterday = Convert.ToString(stDt.SelectedDate.AddDays(-1));
            objCls.cpStDT = todays;
            objCls.cpEndDT = todays;
            objCls.lpStDt = yesterday;
            objCls.lpEndDt = yesterday;
        }

        private void NullLabels_DR()
        {
            errorMessage.Text = "";
            stSumGrid.Visible = true;
        }

        private void NullLabels()
        {
            errorMessage.Text = "";
            stSumGrid.DataSource = null;
            stSumGrid.Visible = false;
        }

        protected void rdDates_SelectedIndexChanged(object sender, EventArgs e)
        {
            stDt.ClearSelection();
            endDt.ClearSelection();
            if (Convert.ToInt32(rdDates.SelectedItem.Value) == 0)
            {
                stDt.MaxDate = DateTime.Today;
                endDt.Visible = false;
                stDt.SelectedDate = DateTime.Today;
                stDt.Enabled = false;
            }
            else
            {
                stDt.MaxDate = DateTime.Today;
                endDt.MaxDate = DateTime.Today;
                endDt.Visible = true;
                stDt.Enabled = true;
                //stDT.SelectedDate = DateTime.Today;
                //endDT.SelectedDate = DateTime.Today;
            }
            stSumGrid.DataSource = null;
            stSumGrid.Visible = false;
            errorMessage.Text = "";
        }

        private void Nulls()
        {

            lblr1.Text = ""; lblr2.Text = ""; lblr3.Text = ""; lblr4.Text = ""; lblr5.Text = ""; lbl_R1.Text = ""; lbl_R2.Text = ""; lbl_R3.Text = ""; lbl_R4.Text = ""; lbl_R5.Text = "";
            errorMessage.Text = "";
        }

        protected void btnProcessTCE_Click(object sender, EventArgs e)
        {
            //SPLongOperation lop = new SPLongOperation(this.Page);
            //lop.LeadingHTML = "<DIV><H2>Report Generation in progress...</H2></DIV>";
            //lop.TrailingHTML = "<DIV><H3>Please wait...</H3></DIV>";
            //lop.Begin();


            if (Convert.ToInt32(rdDates.SelectedItem.Value) == 1)
            {
                if (stDt.SelectedDate > endDt.SelectedDate) { lblDates.Visible = true; lblDates.Text = "Start date should be less than end date"; lblDates.ForeColor = System.Drawing.Color.Red; }
                else { lblDates.Visible = false; lblDates.Text = ""; Processes(); }
            }

            else
            { Processes();  }

            try
            {
                System.Drawing.Color clr = ColorTranslator.FromHtml("#3297fc");
                stSumGrid.Rows[stSumGrid.Rows.Count - 1].BackColor = clr;
            }
            catch (Exception x)
            {
                errorMessage.Text = "Records not found";
                objCls.GetErrorLog(ddlDocsTypes.SelectedItem.Text, x);
            }

            //lop.End("/", Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, string.Empty);
            
        }

        private void Processes()
        {
            string doc = ddlDocsTypes.SelectedItem.Text;
            try
            {
                if (Types == "CNS")
                {
                    if (doc == "AS-BUILT DRAWING SUBMITTALS")
                    {
                        if (ckAsUnderRev.Checked == true)
                            Process_DR();    // Contractor Side
                        else Process_DS();
                    }
                    else if (doc == "Inspection Request")
                    {
                        Process_IRS();      // All
                    }
                    else if (doc == "DRAWING SUBMITTALS")
                    {
                        Process_DOC();
                    }

                    else
                    {
                        Process_IR();      // All
                    }
                }
                else
                {
                    if (doc == "Inspection Requests")
                    {
                        Process_IRS();      // All
                    }
                    else
                    {
                        Process_IR();      // All
                    }

                }
            }
            catch (Exception x)
            {
                errorMessage.Text = "No Records found";
                objCls.GetErrorLog(doc,x);
                stSumGrid.Visible = false;
            }

        }

        protected void stSumGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            stSumGrid.PageIndex = e.NewPageIndex;
            stSumGrid.DataBind();
        }

        protected void ckAsUnderRev_CheckedChanged(object sender, EventArgs e)
        {
            stSumGrid.DataSource = null;
            stSumGrid.Visible = false;
            if (ckAsUnderRev.Checked == true)
            { endDt.Visible = false; }
            if (ckAsUnderRev.Checked)
            {
                rdDates.Items.FindByValue("1").Text = "Based on periods";
                rdDates.Items.FindByValue("0").Text = "Based on periods as of today";
            }
            else
            {
                rdDates.Items.FindByValue("1").Text = "Between Dates";
                rdDates.Items.FindByValue("0").Text = "As of Today";
            }
        }

        protected void ddlDocsTypes_SelectedIndexChanged1(object sender, EventArgs e)
        {
            //if (ddlDocsTypes.SelectedItem.Text == "AS-BUILT DRAWING SUBMITTALS")
            //    ckAsUnderRev.Visible = true;
            //else
            //    ckAsUnderRev.Visible = false;
        }

        protected void ddlDocsTypes_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ddlDocsTypes_SelectedIndexChanged2(object sender, EventArgs e)
        {
            stSumGrid.DataSource = null;
            stSumGrid.Visible = false;

            if (ddlDocsTypes.SelectedItem.Text == "AS-BUILT DRAWING SUBMITTALS" && Types == "CNS")
                ckAsUnderRev.Visible = true;
            else
                ckAsUnderRev.Visible = false;
        }


        protected void btnClear_Click(object sender, EventArgs e)
        {
            stSumGrid.DataSource = null;
            stSumGrid.Visible = false;
            //rdDates.Items.FindByValue("0").Selected = true;
            //endDt.Visible = false;
            //stDt.SelectedDate = DateTime.Today;
            //stDt.Enabled = false;
            EnableControls();
        }

        protected void lnkExport_Click(object sender, EventArgs e)
        {
            this.bexport = true;
        }

        protected override void Render(HtmlTextWriter writer)
        {
            try
            {
                if (Page != null)
                {
                    if (bexport)
                    {
                        stSumGrid.Visible = true;
                        
                        this.bexport = false;
                        Page.Response.Clear();
                        Page.Response.Buffer = true;
                        Page.Response.ContentType = "application/ms-excel";
                        Page.Response.AddHeader("content-disposition", "attachment; filename=Register" + DateTime.Now + ".xls");
                        Page.Response.Charset = "UTF-8";
                        DateTime ct = DateTime.Now;
                        string currentdate = Convert.ToString(ct);
                        string companyname = "tce"; // getCompanyname();
                        HttpContext.Current.Response.Write("<div style='text-align:center'><b>" + companyname + "</b></div>");
                        this.EnableViewState = false;
                        //generateregister();
                        System.IO.StringWriter sw = new System.IO.StringWriter();
                        System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
                        stSumGrid.RenderControl(htw);
                        Page.Response.Write(sw.ToString() + "Register Date : " + currentdate + "");
                        Page.Response.End();

                    }
                }
                base.Render(writer);
            }
            catch (Exception ex)
            {
                //pnlerr.Controls.Add(new LiteralControl("Error in Export to Excel Render Function" + ex.Message));
                //pnlerr.Controls.Add(new LiteralControl("</Br>"));
            }
        }

        private void DisableControls()
        {
            ddlDocsTypes.Enabled = false;
            rdDates.Enabled = false;
            stDt.Enabled = false;
            endDt.Enabled = false;
            btnProcessTCE.Enabled = false;
            ckAsUnderRev.Enabled = false;
        }

        private void EnableControls()
        {
            ddlDocsTypes.Enabled = true;
            rdDates.Enabled = true;
            stDt.Enabled = true;
            endDt.Enabled = true;
            btnProcessTCE.Enabled = true;
            ckAsUnderRev.Enabled = true;
        }

        protected void btnClear_Click3(object sender, EventArgs e)
        {
            EnableControls();
        }

        protected void stSumGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            System.Drawing.Color clr = ColorTranslator.FromHtml("#64b1fd");

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                
                e.Row.Cells[e.Row.Cells.Count - 1].BackColor = clr;//System.Drawing.Color.SkyBlue;
            }

            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[e.Row.Cells.Count - 1].BackColor = clr;//System.Drawing.Color.SkyBlue;
            }
        }
        
        protected void btnLink_Click(object sender, EventArgs e)
        {
            this.bexport = true;
        }

        protected void btnLink_Click2(object sender, EventArgs e)
        {
            this.bexport = true;
        }

      
    }
}
